$(function(){

		// 调用商品放大镜函数
		$(".gs_mediuimg").simpleZoom({
	        zoomBox : ".gs_maximg", 	//需要放大的区域
	        markSize : [270, 180], 		//放大镜宽高
	        zoomSize : [518, 380], 		//需要放大的区域宽高
	        zoomImg : [800, 800] 		//需要放大的区域的图片的宽高
    	});
        var buyNumber = parseInt($('input[name=buynumber]').val());
        //用户商品属性选择--异步获取不同规格的商品的库存
        $('.speclist dd').click(function(){
            $(this).parents('.speclist').children('dd').attr('class' , '');
            $(this).parent().siblings('.speclist').children('dd').removeClass('no');
            $(this).attr('class' , 'on');
            //选中两项符合规格的商品时异步提取对应库存量   
            var ids = $('.speclist dd.on').length;
            var specids='';

            if(ids==2){
                specids+=$(this).attr('id')+','+$(this).parent().siblings('.speclist').children('dd.on').attr('id');
            }else{
                specids = $(this).attr('id');
            }
            //判断商品对应规格是否存在
            var that = $(this);
                $.post(getSpecDataPath ,{'specid' : specids , 'gid' : $('input[name=gsid]').val()} , function(data){
                    eval('var data="' + data+'"');
                    var specs = data.toString(',').split(',');
                    if(ids==2){
                        var inventory = specs.pop();                    
                        if(inventory.substr(0,1)!='i'){
                            specs.push(inventory);
                            $('.specInventory').html('0');
                        }else if(inventory.substr(0,1)=='i'){
                            //获取的对应规格商品的库存数据
                            backData = inventory.substr(1,inventory.length);
                            var priceData = backData.split('|');
                            $('.specInventory').html(priceData[0]);
                            $('.rsprice').html(priceData[1]);
                            //更新商品具体价格时更新小计
                            var num1 = parseFloat($('input[name=buynumber]').val());
                            var num2 = parseFloat(priceData[1]);
                            $('.sump b').html(num1*num2+'.00');
                        }
                    }
                    var specsNum = that.parent().siblings('.speclist').children('dd').length;
                    for(var i = 0; i < specsNum; i++){
                        var index=0;
                        for(var j = 0; j < specs.length ;j++){
                            if(that.parent().siblings('.speclist').children('dd').eq(i).attr('id') != specs[j]){
                                index++;
                            }//判断是否有一次是符合条件的
                            if(index==specs.length){
                                that.parent().siblings('.speclist').children('dd').eq(i).addClass('no');
                            }
                        }
                    }
                },'json');
        });

        //购买数量选择
        //增加
        $('.add').click(function(){
            if(parseInt($('span.specInventory').text()) <= parseInt($('input[name=buynumber]').val())){
                alert('亲，该规格商品剩余库存为'+parseInt($('span.specInventory').text())+'件，您目前最多能购买'+parseInt($('span.specInventory').text())+'件！');
                return false;
            }
            buyNumber++;
            $('input[name=buynumber]').val(buyNumber);
            var num1 = parseFloat(buyNumber);
            var num2 = parseFloat($('.rsprice').text());
            $('.sump b').html(num1*num2+'.00');
        });
        // 减少
        $('.reduce').click(function(){
            buyNumber--;
            if(buyNumber<=0){
                buyNumber=1;
                $('input[name=buynumber]').val(buyNumber);
            }else{
                $('input[name=buynumber]').val(buyNumber);    
            }
            var num1 = parseFloat(buyNumber);
            var num2 = parseFloat($('.rsprice').text());
            $('.sump b').html(num1*num2+'.00');
        });
        //输入购买数量
        var buynu=$('input[name=buynumber]').val();
        $('input[name=buynumber]').change(function(){
            if(/[^\d$]+/.test($(this).val())){
                alert('请输入数字!');
                $(this).val(buynu);
            }else{
                if(parseInt($(this).val())<1){
                    $(this).val('1');
                }
                // alert($('span.specInventory').text());
                if(parseInt($('span.specInventory').text()) < parseInt($(this).val())){
                    alert('亲，该规格商品剩余库存为'+parseInt($('span.specInventory').text())+'件，您目前最多能购买'+parseInt($('span.specInventory').text())+'件！');
                        $(this).val($('span.specInventory').text());
                        return false;
                }
                var num1 = parseFloat($(this).val());
                var num2 = parseFloat($('.rsprice').text());
                $('.sump b').html(num1*num2+'.00');
                buynu=$('input[name=buynumber]').val();
            }
        })

        //关闭提示信息
        $('.ermsg').children('span').click(function(){
            $(this).parent().css('display' , 'none');
            $(this).parent().parent().css('border' , 'none');
        });

        //点击购买时检测用户是否选中商品规格
        $('.buynow').click(function(){
           var specSelected = $('.speclist dd.on').length;
            if(specSelected != 2){
                $('.ermsg').css('display' , 'block');
                $('.gsspec').css('border' ,'2px solid #C30008');
                return false;
            }
            for(var i = 0 ; i < specSelected; i++){
                if($('.speclist dd.on').eq(i).attr('class') !='on'){
                    $('.ermsg').css('display' , 'block');
                    $('.gsspec').css('border' ,'2px solid #C30008');
                    return false;
                }
            }
        });
        // 点击放入购物车时检测用户是否选中商品规格
        $('.ptic').click(function(){
            ajaxCheckGsInfo('ptic');
        });
        //click buynow
        $('a.buynow').click(function(){
            ajaxCheckGsInfo('buynow');
        });

        function ajaxCheckGsInfo(path){
            var specSelected = $('.speclist dd.on').length;
            if(specSelected != 2){
                $('.ermsg').css('display' , 'block');
                $('.gsspec').css('border' ,'2px solid #C30008');
                return false;
            }
            var goodsSpecIds = '';
            for(var i = 0 ; i < specSelected; i++){
                if($('.speclist dd.on').eq(i).attr('class') !='on'){
                    $('.ermsg').css('display' , 'block');
                    $('.gsspec').css('border' ,'2px solid #C30008');
                    return false;
                }
                goodsSpecIds+=','+$('.speclist dd.on').eq(i).attr('id');
            }
            //ajax post buy goodsinfo
            $.post(toCartPath , {'goodsSpecIds' : goodsSpecIds , 'gid': $('input[name=gsid]').val() , 'number' :$('input[name=buynumber]').val()} , function (data){
                eval('var data = data');
                if(data.status == 'er'){
                    alert('您请求的商品信息有误,请重试！');
                    return false;
                }else if(data.status == 'ok'){
                    //updata buycart's data
                    $('span.gsnum').text(data.cartGsNum);
                    $('font.tcartgsnum').text(data.cartGsNum);
                    buyCartShow();
                    //updata buycart's contents
                    var buyCartStr = '';
                    for(var i=0 ; i<data.cartUseGsInfo.length ; i++){
                        buyCartStr +='<li cartlid="'+i+'"><a href="'+GsPath+data.cartUseGsInfo[i].gid+'" title="'+data.cartUseGsInfo[i].gname+'"><img src="'+data.cartUseGsInfo[i].gimg+'" width="45px" height="45px" /></a><p><a href="'+GsPath+data.cartUseGsInfo[i].gid+'" title="'+data.cartUseGsInfo[i].gname+'">'+data.cartUseGsInfo[i].gname+'</a></p><p class="delcartgs">x</p><p>'+data.cartUseGsInfo[i].color+'&nbsp;&nbsp;'+data.cartUseGsInfo[i].size+'&nbsp;&nbsp;￥'+data.cartUseGsInfo[i].sprice+'&nbsp;&nbsp;x&nbsp;&nbsp;'+data.cartUseGsInfo[i].number+'</p></li>';
                    }
                    $('ul.cartgslist_c').empty().append(buyCartStr);
                    if(path == 'buynow'){
                        location.href=buyNowPath;
                    }else if(path == 'ptic'){
                        $('div#wherego').css('display','block');
                    }
                }
            },'json');
        }

        //商品展示图处理
        //商品缩略图默认第一小图为选中加边框状态
        if($('.gs_miniimg li').length > 0){
            $('.gs_miniimg li:first-child a img').css('border' , '1px solid #C30008');
        }
        //根据选择的商品缩略图替换商品中图和放大图
        $('.gs_miniimg li').mousemove(function(){
            $('.minipic').css('border' , '1px solid #CCCCCC');
            $(this).children('a').children('img').css('border' , '1px solid #C30008');
            var replaceMediumImg =  $('.gs_mediuimg imgs').eq($(this).index()).attr('src');
            var replaceMaxImg =  $('.gs_maximg imgs').eq($(this).index()).attr('src');
            $('.gs_mediuimg img').attr('src' , replaceMediumImg);
            $('.gs_maximg img').attr('src' , replaceMaxImg);
        });

        //close goods to cart success message
        $('div.good_Car_topCOlose').click(function(){
            $('div#wherego').css('display','none');
        });
});

// 商品图放大镜插件函数
(function($){
    $.fn.simpleZoom = function(options){
        var defs = {
            zoomBox : "#zoomBox",           //需要放大的区域
            markSize : [200, 200],          //放大镜宽高
            zoomSize : [400, 400],          //需要放大的区域宽高
            zoomImg : [800, 800]            //需要放大的区域的图片的宽高
        };
        var opt = $.fn.extend({}, defs, options);
        return this.each(function(){
            var markBox = $(this);
            var zoomBox = $(opt.zoomBox);
            var zoom_img = $(opt.zoomBox).find("img"); 
            var markBoxSize = [markBox.width(), markBox.height(), markBox.offset().left, markBox.offset().top];
            var markSize = opt.markSize;
            var zoomSize = opt.zoomSize;
            var zoomImg = opt.zoomImg;
            var mark_ele = "<i id='mark'></i>";
            var mark_css = {position:"absolute", top:0, left:0, width:markSize[0]+"px", height:markSize[1]+"px", background: 'url('+imgspath+'T12pdtXaldXXXXXXXX-2-2.png) repeat', opacity:.8, filter:"alpha(opacity=80)",  display:"none", cursor:"move"};
            
            var show_w = markBoxSize[0]-markSize[0];
            var show_h = markBoxSize[1]-markSize[1];

            //created mark element and add cascading style sheets
            zoomBox.css({width:zoomSize[0]+"px", height:zoomSize[1]+"px"});
            markBox.append(mark_ele);
            $("#mark").css(mark_css);

            markBox.mouseover(function(){
                $("#mark").show();
                zoomBox.show();
            }).mouseout(function(){
                $("#mark").hide();
                zoomBox.hide();
            }).mousemove(function(e){
                var l = e.pageX-markBoxSize[2]-(markSize[0]/2);
                var t = e.pageY-markBoxSize[3]-(markSize[1]/2);
                if(l < 0){
                    l = 0;
                }else if(l > show_w){
                    l = show_w;
                }
                if(t < 0){
                    t = 0;
                }else if(t > show_h){
                    t = show_h;
                }

                $("#mark").css({left:l+"px", top:t+"px"});
                
                var z_x = -(l/show_w)*(zoomImg[0]-zoomSize[0]);
                var z_y = -(t/show_h)*(zoomImg[1]-zoomSize[1]);
                zoom_img.css({left:z_x+"px", top:z_y+"px"});
            });
        });
    }
})(jQuery);